<script setup lang="ts">
import { onBeforeMount, onMounted, reactive, ref, unref } from 'vue'
import { useBaseApi } from '@/api/base'
import { useRoute } from 'vue-router'
import { Position, Search } from '@element-plus/icons-vue'
import type { VxeToolbarProps } from 'vxe-table'
import type {
  BusinessUIAction,
  BusinessUIFormType,
  BusinessUIQueryType,
  BusinessUITableType,
  DicType,
  WorkflowDesignRow
} from '@/types/custom'

import TemplateVxeGrid from '@/views/components/grid/components/TemplateVxeGrid.vue'
import { onFetchUser } from '@/views/components/form/libs'
import { dayjs, ElMessage, ElMessageBox, type FormInstance } from 'element-plus'

interface Props {
  disabled?: boolean
  insert?: boolean
  boxShadow?: boolean
}

const route = useRoute()

const props = defineProps<Props>()

const emit = defineEmits(['fetch', 'close'])

const modelValue = defineModel<string>()

const { get_business_ui, CustomRequest } = useBaseApi()

// 表单
const ruleForm = ref<FormInstance>()
// 部门-用户
const userItems = ref<SelectOptionType[]>([])
// 加载
const loading = ref(false)
// 业务ID
// const business_id = ref(String(route.meta.id))
// const business_id = ref('16706979-d974-4df0-ab6e-5912be70ae79')
// const business_id = ref('53376fde-f7b3-4753-8440-0c3b9d463e9d')
// const business_id = ref('0cd174b6-fb5f-4e40-96a8-2c0b0afe6c3f')
// const business_id = ref('home')
// 查询栏
const uiQuery = ref<BusinessUIQueryType | undefined>()
// 表格
const uiTable = ref<BusinessUITableType | undefined>()
// 表单
const uiForm = ref<BusinessUIFormType | undefined>()
// 表单字典
const dicTable = ref<DicType[]>([])
// 查询字典
const dicQuery = ref<DicType[]>([])
// 薪酬按钮配置
const uiActions = ref<BusinessUIAction[]>([])
// 当前业务的按钮配置
const baseUiActions = ref<BusinessUIAction[]>([])
// 关联流程
const wfDesign = ref<WorkflowDesignRow | undefined>()
// 表格
const gridRef = ref()
// 工具栏配置
const toolbarConfig = ref<VxeToolbarProps>({})
// 查询栏
const state = reactive({
  year_month: '',
  user_id: ''
})

// /**
//  * 初始化mitt事件
//  */
// const onEventMitt = () => {
//   if (uiTable.value && ['sys_workflow_list', 'sys_user_msg'].includes(uiTable.value.id)) {
//     mittBus.on('onUpdateMsg', () => {
//       onFetch()
//     })
//   }
// }

/**
 * 格式化默认参数
 */
const onDefaultFetch = async () => {
  const id = unref(modelValue)
  if (!id) return
  loading.value = true
  const baseBusiness = await get_business_ui(route.meta.id, true)
  baseUiActions.value = baseBusiness.data.actions || []
  await get_business_ui(id, true)
    .then(({ data }) => {
      const dic_table = data.dic_table || []
      const dic_query = data.dic_query || []
      const ui_table = data.ui_table
      const ui_query = data.ui_query
      const ui_form = data.ui_form
      const ui_actions = props.disabled ? [] : data.actions || []
      const wf_design = data.wf_design
      if (ui_table) {
        const { default_value_parse } = ui_table
        if (baseBusiness.data.ui_table) {
          const { api, method, pagination } = baseBusiness.data.ui_table
          ui_table.pagination = pagination
          ui_table.api = api
          ui_table.method = method
        }
        uiTable.value = ui_table

        if (default_value_parse.toolbarConfig)
          toolbarConfig.value = default_value_parse.toolbarConfig
      }
      if (ui_query) uiQuery.value = ui_query
      if (ui_form) uiForm.value = ui_form

      dicQuery.value = dic_query
      dicTable.value = dic_table
      wfDesign.value = wf_design
      uiActions.value = ui_actions

      // params.method = ui_table?.method || 'post'
      // params.data = params.method.toLowerCase() === 'post' ? clone(defaultParamData, true) : {}
      // params.params = params.method.toLowerCase() === 'get' ? clone(defaultParamData, true) : {}
      // params.url = ui_table?.api
      // onEventMitt()
      // setTimeout(() => {
      //   onFetch()
      // }, 500)
    })
    .finally(() => (loading.value = false))
}

const onFetch = () => {
  ruleForm.value?.validate((valid) => {
    if (valid) {
      loading.value = true
      if (gridRef.value) {
        gridRef.value.onFetch(state).finally(() => (loading.value = false))
      } else {
        loading.value = false
      }
    }
  })
}

const payOutWages = (action: BusinessUIAction) => {
  ElMessageBox.confirm('此操作将发放工资，是否继续？', '提示', {
    confirmButtonText: '确认发放',
    cancelButtonText: '取消',
    beforeClose: (key, instance, done) => {
      if (key === 'confirm') {
        instance.confirmButtonLoading = true
        instance.confirmButtonText = '执行中...'
        CustomRequest({
          url: action.api,
          method: action.method,
          params: action.method === 'get' ? state : {},
          data: action.method === 'post' ? state : {}
        })
          .then(() => {
            ElMessage.success('执行成功！')
          })
          .finally(done)
        // PostMonthPay(state)
        //   .then(() => {
        //     ElMessage.success('执行成功！')
        //   })
        //   .finally(done)
      } else {
        done()
      }
    }
  })
    .then(() => {})
    .catch(() => {})
}

onBeforeMount(() => {
  if (route.query.id) {
    modelValue.value = String(route.query.id)
  } else if (!modelValue.value) modelValue.value = '21fa49e4-edfd-44c9-98d0-bec030fb1523'
  onDefaultFetch()

  state.year_month = dayjs().subtract(1, 'month').format('YYYY-MM')
})

onMounted(() => {
  onFetchUser([], state).then((data) => {
    userItems.value = data
  })
})

defineExpose({ onFetch })
</script>

<template>
  <TemplateVxeGrid
    ref="gridRef"
    v-model="loading"
    :params="state"
    :toolbar-config="toolbarConfig"
    :ui-form="uiForm"
    :ui-table="uiTable"
    :ui-query="uiQuery"
    :dic-query="dicQuery"
    :dic-table="dicTable"
    :ui-actions="uiActions"
    :wf-design="wfDesign"
    :box-shadow="boxShadow"
    :insert="insert"
    @close="emit('close')"
    @fetch="emit('fetch')"
    empty-text="点击薪资预览查询列表"
  >
    <div class="salary-query w100 pa5">
      <el-form :model="state" ref="ruleForm" inline>
        <el-form-item
          prop="year_month"
          required
          :rules="[{ required: true, message: '请选择月份', trigger: 'change' }]"
        >
          <el-date-picker
            v-model="state.year_month"
            type="month"
            placeholder="请选择月份"
            value-format="YYYY-MM"
            style="width: 150px"
          />
        </el-form-item>
        <!--        <el-form-item prop="user_id">-->
        <!--          <el-tree-select-->
        <!--            v-model="state.user_id"-->
        <!--            :data="userItems"-->
        <!--            clearable-->
        <!--            filterable-->
        <!--            collapseTags-->
        <!--            checkStrictly-->
        <!--            collapseTagsTooltip-->
        <!--            defaultExpandAll-->
        <!--            placeholder="请选择员工"-->
        <!--            style="min-width: 150px"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <el-form-item>
          <el-button :icon="Search" @click="onFetch" :loading="loading"> 薪资预览 </el-button>
          <el-button
            v-for="(action, index) in baseUiActions"
            :key="index"
            :icon="Position"
            :type="action.type"
            @click="payOutWages(action)"
            :loading="loading"
            class="ml5"
          >
            {{ action.name }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </TemplateVxeGrid>
</template>

<style lang="scss">
.salary-query {
  background-color: var(--el-bg-color);
  border-radius: 8px 8px 0 0;
  transform: translateX(5px);

  .el-form--inline .el-form-item {
    margin-right: 5px !important;
    margin-bottom: 0 !important;
  }

  .el-form.el-form--inline .el-form-item--small.el-form-item:last-of-type {
    margin-bottom: 0 !important;
  }
}
</style>
